package com.ruoyi.project.ledger.service.impl;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ExportUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.ledger.domain.LedgerFile;
import com.ruoyi.project.ledger.domain.LedgerManagementRegistration;
import com.ruoyi.project.ledger.domain.LedgerWorker;
import com.ruoyi.project.ledger.mapper.LedgerFileMapper;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.ledger.mapper.LedgerSafetyEducationMapper;
import com.ruoyi.project.ledger.domain.LedgerSafetyEducation;
import com.ruoyi.project.ledger.service.ILedgerSafetyEducationService;

/**
 * 安全教育活动台账Service业务层处理
 *
 * @author gwc
 * @date 2020-04-14
 */
@Service
public class LedgerSafetyEducationServiceImpl implements ILedgerSafetyEducationService
{
    @Autowired
    private LedgerSafetyEducationMapper ledgerSafetyEducationMapper;
    @Autowired
    private LedgerFileMapper ledgerFileMapper;
    @Autowired
    private ServerConfig serverConfig;

    /**
     * 查询安全教育活动台账
     *
     * @param id 安全教育活动台账ID
     * @return 安全教育活动台账
     */
    @Override
    public LedgerSafetyEducation selectLedgerSafetyEducationById(Long id)
    {
        LedgerSafetyEducation education = ledgerSafetyEducationMapper.selectLedgerSafetyEducationById(id);
        if(education != null){
            // 获取图片
            LedgerFile ledgerFile = new LedgerFile();
            ledgerFile.setLedgerId(id);
            ledgerFile.setLedgerType("4");      // 安全教育活动台账
            List<Map<String, Object>> imgList = ledgerFileMapper.selectLedgerImgList(ledgerFile);
            education.setImgList(imgList);
        }
        return education;
    }

    /**
     * 查询安全教育活动台账列表
     *
     * @param ledgerSafetyEducation 安全教育活动台账
     * @return 安全教育活动台账
     */
    @Override
    public List<LedgerSafetyEducation> selectLedgerSafetyEducationList(LedgerSafetyEducation ledgerSafetyEducation)
    {
        return ledgerSafetyEducationMapper.selectLedgerSafetyEducationList(ledgerSafetyEducation);
    }

    /**
     * 新增安全教育活动台账
     *
     * @param ledgerSafetyEducation 安全教育活动台账
     * @return 结果
     */
    @Override
    public int insertLedgerSafetyEducation(LedgerSafetyEducation ledgerSafetyEducation)
    {
        ledgerSafetyEducation.setCreateTime(DateUtils.getNowDate());
        if(ledgerSafetyEducation.getActivityDate() != null){
            ledgerSafetyEducation.setActivityWeek(DateUtils.dateToWeek(DateUtils.dateTime(ledgerSafetyEducation.getActivityDate())));
        }
        int i = ledgerSafetyEducationMapper.insertLedgerSafetyEducation(ledgerSafetyEducation);
        // 添加图片
        if(ledgerSafetyEducation.getImgs() != null && ledgerSafetyEducation.getImgs().length > 0){
            for(String path : ledgerSafetyEducation.getImgs()){
                LedgerFile ledgerFile = new LedgerFile();
                ledgerFile.setLedgerType("4");    // 安全教育活动台账
                ledgerFile.setLedgerId(ledgerSafetyEducation.getId());
                ledgerFile.setFilePath(path);
                ledgerFile.setCreateId(ledgerSafetyEducation.getCreateId());
                ledgerFile.setCreateTime(DateUtils.getNowDate());
                ledgerFileMapper.insertLedgerFile(ledgerFile);
            }
        }
        // 添加参加人员
//        if(ledgerSafetyEducation.getWorkerIds() != null && ledgerSafetyEducation.getWorkerIds().length > 0){
//            List<LedgerWorker> ledgerWorkerList = new ArrayList<>();
//            for(Long workerId : ledgerSafetyEducation.getWorkerIds()){
//                LedgerWorker ledgerWorker = new LedgerWorker();
//                ledgerWorker.setWorkerId(workerId);
//                ledgerWorker.setLedgerId(ledgerSafetyEducation.getId());
//                ledgerWorker.setWorkerType("1");    //场站人员
//                ledgerWorkerList.add(ledgerWorker);
//            }
//            if(ledgerWorkerList.size() > 0){
//                ledgerSafetyEducationMapper.batchAddAttendWorker(ledgerWorkerList);
//            }
//        }
        return i;
    }

    /**
     * 修改安全教育活动台账
     *
     * @param ledgerSafetyEducation 安全教育活动台账
     * @return 结果
     */
    @Override
    public int updateLedgerSafetyEducation(LedgerSafetyEducation ledgerSafetyEducation)
    {
        ledgerSafetyEducation.setUpdateTime(DateUtils.getNowDate());
        if(ledgerSafetyEducation.getActivityDate() != null){
            ledgerSafetyEducation.setActivityWeek(DateUtils.dateToWeek(DateUtils.dateTime(ledgerSafetyEducation.getActivityDate())));
        }
        int i = ledgerSafetyEducationMapper.updateLedgerSafetyEducation(ledgerSafetyEducation);
        // 删除台账图片
        LedgerFile ledgerFile = new LedgerFile();
        ledgerFile.setLedgerId(ledgerSafetyEducation.getId());
        ledgerFile.setLedgerType("4");      // 安全教育活动台账
        ledgerFileMapper.deleteLedgerImg(ledgerFile);
        if(ledgerSafetyEducation.getImgs() != null && ledgerSafetyEducation.getImgs().length > 0){
            for(String path : ledgerSafetyEducation.getImgs()){
                ledgerFile = new LedgerFile();
                ledgerFile.setLedgerType("4");    // 安全教育活动台账
                ledgerFile.setLedgerId(ledgerSafetyEducation.getId());
                ledgerFile.setFilePath(path);
                ledgerFile.setCreateId(ledgerSafetyEducation.getUpdateId());
                ledgerFile.setCreateTime(DateUtils.getNowDate());
                ledgerFileMapper.insertLedgerFile(ledgerFile);
            }
        }
        return i;
    }

    /**
     * 批量删除安全教育活动台账
     *
     * @param ids 需要删除的安全教育活动台账ID
     * @return 结果
     */
    @Override
    public int deleteLedgerSafetyEducationByIds(Long[] ids)
    {
        int i = ledgerSafetyEducationMapper.deleteLedgerSafetyEducationByIds(ids);
        for(Long id : ids){
            // 删除台账图片
            LedgerFile ledgerFile = new LedgerFile();
            ledgerFile.setLedgerId(id);
            ledgerFile.setLedgerType("4");      // 安全教育活动台账
            ledgerFileMapper.deleteLedgerImg(ledgerFile);
        }
        return i;
    }

    /**
     * 删除安全教育活动台账信息
     *
     * @param id 安全教育活动台账ID
     * @return 结果
     */
    @Override
    public int deleteLedgerSafetyEducationById(Long id)
    {
        int i = ledgerSafetyEducationMapper.deleteLedgerSafetyEducationById(id);
        // 删除台账图片
        LedgerFile ledgerFile = new LedgerFile();
        ledgerFile.setLedgerId(id);
        ledgerFile.setLedgerType("4");      // 安全教育活动台账
        ledgerFileMapper.deleteLedgerImg(ledgerFile);
        return i;
    }

    /**
     *
     * @param ledgerWorker
     * @return
     */
    @Override
    public List<LedgerWorker> selectNoAttendWorkerList(LedgerWorker ledgerWorker) {
        return ledgerSafetyEducationMapper.selectNoAttendWorkerList(ledgerWorker);
    }

    @Override
    public List<LedgerWorker> selectAttendWorkerList(LedgerWorker ledgerWorker) {
        return ledgerSafetyEducationMapper.selectAttendWorkerList(ledgerWorker);
    }

    @Override
    public List<LedgerManagementRegistration> selectAttendees(LedgerManagementRegistration managementRegistration) {
        return ledgerSafetyEducationMapper.selectAttendees(managementRegistration);
    }

    @Override
    public List<LedgerManagementRegistration> selectNoAttendees(LedgerManagementRegistration managementRegistration) {
        return ledgerSafetyEducationMapper.selectNoAttendees(managementRegistration);
    }

    @Override
    public int addAttendWorker(LedgerSafetyEducation ledgerSafetyEducation) {
        int i = 0;
        // 添加参加人员
        if(ledgerSafetyEducation.getWorkerIds() != null && ledgerSafetyEducation.getWorkerIds().length > 0){
            List<LedgerWorker> ledgerWorkerList = new ArrayList<>();
            for(Long workerId : ledgerSafetyEducation.getWorkerIds()){
                LedgerWorker ledgerWorker = new LedgerWorker();
                ledgerWorker.setWorkerId(workerId);
                ledgerWorker.setLedgerId(ledgerSafetyEducation.getId());
                ledgerWorker.setWorkerType("1");    //场站人员
                ledgerWorkerList.add(ledgerWorker);
            }
            if(ledgerWorkerList.size() > 0){
                i = ledgerSafetyEducationMapper.batchAddAttendWorker(ledgerWorkerList);
            }
        }
        return i;
    }

    @Override
    public int deleteAttendWorker(Long id) {
        return ledgerSafetyEducationMapper.deleteAttendWorker(id);
    }

    @Override
    public AjaxResult exportDetail(Long id) {
        LedgerSafetyEducation education = ledgerSafetyEducationMapper.selectLedgerSafetyEducationById(id);
        if (education == null) {
            return AjaxResult.error("当前台账信息不存在");
        }
        // 获取图片
        LedgerFile ledgerFile = new LedgerFile();
        ledgerFile.setLedgerId(id);
        ledgerFile.setLedgerType("4");      // 安全教育活动台账
        List<Map<String, Object>> imgList = ledgerFileMapper.selectLedgerImgList(ledgerFile);
        education.setImgList(imgList);

//        // 获取参加人员列表
//        List<LedgerWorker> workers = ledgerSafetyEducationService.selectAttendWorkerList(new LedgerWorker(id));
        List<Map<String, Object>> list1 = new ArrayList<>();
        int j = 0;
//        if (workers != null && workers.size() >0){
//            Map<String,Object> map = new HashMap<>();
//            int size = workers.size();
//            for (int i=0; i < size;i=i+2){
//                map.put("company",education.getStationName());
//                map.put("name",workers.get(i).getName());
//                map.put("post","场站人员");
//                if (size>i+1){
//                    map.put("company1",education.getStationName());
//                    map.put("name1",workers.get(i+1).getName());
//                    map.put("post1","场站人员");
//                }else {
//                    map.put("company1","");
//                    map.put("name1","");
//                    map.put("post1","");
//                }
//                j++;
//                list1.add(map);
//            }
//        }
        if (education.getToBePeople() != null) {
            Map<String, Object> map = new HashMap<>();
            int size = education.getToBePeople().intValue();
            for (int i = 0; i < size; i = i + 2) {
                map.put("company", "");
                map.put("name", "");
                map.put("post", "");
                if (size > i + 1) {
                    map.put("company1", "");
                    map.put("name1", "");
                    map.put("post1", "");
                } else {
                    map.put("company1", "");
                    map.put("name1", "");
                    map.put("post1", "");
                }
                j++;
                list1.add(map);
            }

        }

        String tplPath = this.getClass().getResource("/").getPath() + "excel/安全教育培训活动台账.xls";
        String fileName = "安全教育培训活动台账.xls";

        //fileName = FileUtils.setFileDownloadHeader(request, fileName);

        Map<String, Object> beanParams = new HashMap<String, Object>();
        beanParams.put("education", education);
        beanParams.put("list", list1);
        beanParams.put("year", new SimpleDateFormat("yyyy").format(education.getActivityDate()));
        beanParams.put("month", new SimpleDateFormat("MM").format(education.getActivityDate()));
        beanParams.put("day", new SimpleDateFormat("dd").format(education.getActivityDate()));
        beanParams.put("activityDate", new SimpleDateFormat("HH:mm").format(education.getActivityDate()));
        beanParams.put("activityWeek", education.getActivityWeek().substring(education.getActivityWeek().length() - 1, education.getActivityWeek().length()));

        XLSTransformer former = new XLSTransformer();
        InputStream in = null;
        OutputStream out = null;
        Workbook workbook = null;
        try {
            in = new BufferedInputStream(new FileInputStream(tplPath));
            workbook = former.transformXLS(in, beanParams);
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(fileName));
            if (education.getImgList() != null && education.getImgList().size() > 0) {
                int i = 0;
                int k=0;
                for (int m=0;m<education.getImgList().size();m++){
                    if (m<3){
                        if (StringUtils.isNotBlank(String.valueOf(education.getImgList().get(m).get("url")))) {
                            ExportUtil.createPicture(serverConfig.getUrl()+education.getImgList().get(m).get("url"), workbook, "Sheet1", (short) (i), 13 + j, (short) (i + 2), 14 + j);
                        }
                        i = i + 2;
                    }else {
                        if (StringUtils.isNotBlank(String.valueOf(education.getImgList().get(m).get("url")))) {
                            ExportUtil.createPicture(serverConfig.getUrl()+education.getImgList().get(m).get("url"), workbook, "Sheet1", (short) (k), 14 + j, (short) (k + 2), 15 + j);
                        }
                        k = k + 2;
                    }

                }
            }
            workbook.write(out);
            return AjaxResult.success(fileName);
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
        return AjaxResult.error("导出失败");
    }
}
